import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Icon, Input, Button, Select, Row, Col, message } from 'antd'
const Option = Select.Option;
const FormItem = Form.Item;

import 'styles/expense-reimbursement-control/reimbursement/edit-control.scss'
import reimburseService from 'containers/expense-reimbursement-control/expense-standard/reimbursement/reimbursement.service'
import errorMessage from 'share/errorMessage'

class EditControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      conditions: deepFullCopy(props.params.conditions),
      operatorOptions: [
        {sign: '+', operatorId: 1001},
        {sign: '-', operatorId: 1002},
        {sign: '*', operatorId: 1004},
        {sign: '/', operatorId: 1003}
      ],
      ruleOptions: [
        {id: 'DAYS', label: messages('expense-reimbursement-control.key5')/*入住天数*/, description: messages('expense-reimbursement-control.key6')/*统计费用上[开始结束日期]计算出的天数。如费用类型中未配置该控件或配置了但值为空，则会按照“0”处理*/},
        {id: 'PEOPLES', label: messages('expense-reimbursement-control.key7')/*人数*/, description: messages('expense-reimbursement-control.key8')/*统计费用上[参与人]中包含的人数。如费用类型中未配置该控件或配置了但值为空，则会按照“1”处理*/},
        {id: 'ROOMS', label: messages('expense-reimbursement-control.key9')/*房间数*/, description: messages('expense-reimbursement-control.key10')/*按照费用上[参与人]中包含的人员计算房间数。房间数=(X/2)向上取整+(Y/2)向上取整+Z+Q。其中，X/Y/Z/Q分别为：参与人中“男性”/“女性”/“性别未知或空值”/“不参与同住管控的人员”的人数。如费用类型中未配置该控件或配置了但值为空，则会按照“1”处理*/}
      ],
    };
  }

  componentDidMount() {
    let { conditions } = this.state;
    conditions.map((item, index) => item.id = index + 1);
    this.setState({ conditions })
  }

  //添加条件
  handleAddOperator = () => {
    let { conditions } = this.state;
    conditions.map((item, index) => item.id = index + 1);
    conditions.push({operatorId: 1004, rightFieldCode: 'DAYS', id: conditions.length + 1});
    this.setState({ conditions })
  };

  //修改运算符或条件值
  handleChangeCondition = (id, value, type) => {
    let { conditions } = this.state;
    if (type === 'rightFieldCode') {
      if (!~['DAYS', 'PEOPLES', 'ROOMS'].indexOf(value) && isNaN(value)) {
        value = undefined
      }
    }
    conditions.map(item => {
      item.id === id && (item[type] = value)
    });
    this.setState({ conditions })
  };

  //删除条件
  handleDelete = (id) => {
    let { conditions } = this.state;
    conditions.map((item, index) => {
      item.id === id && conditions.splice(index, 1)
    });
    this.setState({ conditions })
  };

  handleSave = () => {
    let { conditions } = this.state;
    let hasEmpty = false;
    conditions.map(item => !item.rightFieldCode && (hasEmpty = true));
    if (hasEmpty) {
      message.error(messages('expense-reimbursement-control.key11')/*条件不能为空*/);
      return
    }
    conditions.map(item => {
      delete item.id;
      if (!~['DAYS', 'PEOPLES', 'ROOMS', 'CUSTOM_NUMBER'].indexOf(item.rightFieldCode)) {
        item.positiveNumber = item.rightFieldCode;
        item.rightFieldCode = 'CUSTOM_NUMBER'
      }
    });
    this.setState({ loading: true });
    reimburseService.updateControlInfo(this.props.params.ruleOID, conditions).then(() => {
      this.setState({ loading: false });
      message.success(messages('common.save.success', {name: ""})/*保存成功*/);
      this.props.close('control')
    }).catch(e => {
      errorMessage(e.response);
      conditions.map((item, index) => item.id = index + 1);
      this.setState({ loading: false, conditions })
    })
  };

  render(){
    const { loading, conditions, ruleOptions, operatorOptions } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12, offset: 1 }
    };
    return (
      <div className="edit-control">
        <Form>
          <FormItem {...formItemLayout}
                    label={<span className="ant-form-item-required">{messages('expense-reimbursement-control.key12')/*管控项*/}</span>}>
            <Input value={messages('expense-reimbursement-control.key13')/*费用金额*/} disabled/>
          </FormItem>
          <FormItem {...formItemLayout}
                    label={<span className="ant-form-item-required">{messages('expense-reimbursement-control.key14')/*取值方式*/}</span>}>
            <Input value=">" disabled/>
          </FormItem>
          <FormItem {...formItemLayout}
                    label={<span className="ant-form-item-required">{messages('expense-reimbursement-control.key15')/*条件*/}</span>}>
            <Input value={messages('expense-reimbursement-control.key16')/*基本标准*/} disabled/>
          </FormItem>
          {conditions.map(item => (
            <Row key={item.id} className="condition-row">
              <Col span={12} offset={9}>
                <Row gutter={20}>
                  <Col span={8}>
                    <Select value={Number(item.operatorId)}
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            onChange={value => this.handleChangeCondition(item.id, value, 'operatorId')}>
                      {operatorOptions.map(item => (
                        <Option value={item.operatorId} key={item.operatorId}>{item.sign}</Option>
                      ))}
                    </Select>
                  </Col>
                  <Col span={16}>
                    <Select mode="combobox"
                            value={item.rightFieldCode === 'CUSTOM_NUMBER' ? String(item.positiveNumber) : item.rightFieldCode}
                            optionLabelProp="title"
                            getPopupContainer={() => document.getElementsByClassName('edit-control')[0]}
                            onChange={value => this.handleChangeCondition(item.id, value, 'rightFieldCode')}>
                      {ruleOptions.map(optionItem => (
                        <Option key={optionItem.id} title={optionItem.label} className="new-control-select-option">
                          <div>
                            <div>{optionItem.label}</div>
                            <div className="description">{optionItem.description}</div>
                          </div>
                        </Option>
                      ))}
                    </Select>
                  </Col>
                </Row>
              </Col>
              <Icon onClick={() => this.handleDelete(item.id)} type="minus-circle" className="delete-operator-item"/>
            </Row>
          ))}
          <FormItem {...formItemLayout} label=" " colon={false}>
            <div className="new-operator-item" onClick={this.handleAddOperator}>
              <Icon type="plus" /> {messages('expense-reimbursement-control.key17')/*添加条件*/}
            </div>
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={() => this.props.close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    language: state.main.language
  }
}

const WrappedEditControl = Form.create()(EditControl);

export default connect(mapStateToProps)(WrappedEditControl);

